<template>
  <!-- 搜索和地图容器 -->
  <div style="position: relative">
    <!-- 地图搜索组件 -->
    <div class="mapSearch">
      <!-- 输入框用于输入搜索关键词 -->
      <el-input placeholder="请输入你要查找的关键词" v-model="userInput" id="tishikuang"/>
      <!-- 确定选址按钮，点击触发biu方法 -->
      <el-button type="primary" @click="biu">确定选址</el-button>
    </div>
    <!-- 地图容器 -->
    <div id="container">
    </div>
    <div style="position: absolute;top: 10%;right: 15%" id="panel"></div>
  </div>
</template>

<script>
// 引入高德地图加载器
import AMapLoader from '@amap/amap-jsapi-loader'

// 配置高德地图安全密钥
window._AMapSecurityConfig = {
  securityJsCode: '69131a1aa42d05dcd72464e784a4037c'//在这里填写你的安全密钥
}
export default {
  data() {
    return {
      map: null,
      driving: null,
      autoOptions: {
        input: 'tishikuang' //绑定的搜索关键字的input标签ID，用这个注册
      },
      auto: null,
      userInput: '', //绑定的搜索关键字的内容
      placeSearch: null,
      searchHere: null, //根据搜索组件搜索到以后的地点信息
    }
  },
  props: {
    location: {
      type: String,
      require: true
    }
  },
  watch: {
    location: {
      handler(newLocation) {
        if (newLocation) {
          const addressList = newLocation.split(',');
          // 构造完整地址（根据高德地图格式要求）
          const fullAddress = addressList[addressList.length - 2] + addressList[addressList.length - 1];

          // 使用地理编码服务
          // eslint-disable-next-line no-undef
          const geocoder = new AMap.Geocoder({
            city: addressList[0], // 限定城市
          });
          let location;
          geocoder.getLocation(fullAddress, (status, result) => {
            if (status === 'complete' && result.geocodes.length) {
              location = result.geocodes[0].location;
              this.map.setCenter(location);
              this.searchHere = {
                name: fullAddress,
                location: location
              };
            }
          });

          // 根据起终点名称规划驾车导航路线
          this.driving.search([
            {keyword: '湖南省张家界市', city: '湖南省'},
            {
              keyword: addressList[addressList.length - 2] + addressList[addressList.length - 1],
              city: addressList[addressList.length - 2]
            }
          ], function (status, result) {
            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
              console.log('绘制驾车路线完成')
            } else {
              console.log('获取驾车数据失败：' + result)
            }
          });
        }
      },
      // immediate: true,
      deep: true
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    // poi搜索以后 点击确认选址以后的操作
    biu() {
      if (this.searchHere) {
        this.$message({
          message: '确认地点：' + this.searchHere.name,
          type: 'success'
        });
      }
    },

    // 初始化地图方法
    initMap() {
      AMapLoader.load({
        key: "413ea41e1585976f268cbc06d152917c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          'AMap.Driving',
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.HawkEye',
          'AMap.MapType',
          'AMap.Geolocation',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.Geocoder'
        ], // 需要使用的的插件列表
      }).then((AMap) => {
        this.map = new AMap.Map("container", { //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 17, //初始化地图级别
          center: [105.602725, 37.076636], //初始化地图中心点位置
        });

        //构造路线导航类
        this.driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });

        // 引入高德地图的空间绑定使用
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.HawkEye());
        this.map.addControl(new AMap.MapType());
        this.map.addControl(new AMap.Geolocation());

        this.auto = new AMap.AutoComplete(this.autoOptions);
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map
        }); //构造地点查询类
        this.auto.on('select', this.select); //绑定查询事件
        this.geocoder = new AMap.Geocoder(); // 创建地理编码实例
      }).catch(e => {
        console.error('地图加载失败:', e);
      });
    },

    // poi搜索 这里面的这个参数 e 就是搜索以后的地址信息 你可以把它打印出来看一看经纬度什么的都有
    select(e) {
      // 处理来自watch的地理编码结果
      if (e.type === 'geocoder') {
        this.map.setCenter(e.location);
        this.searchHere = {
          name: e.address,
          location: e.location
        };
        return;
      }

      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name);

      this.placeSearch.setCity(e.poi.adcode); //依据城市ID搜索
      this.placeSearch.search(e.poi.name); //关键字查询查询
      this.map.setZoom(10, true);
      this.searchHere = e.poi;
      this.$message({
        message: '选择地点:' + this.searchHere.name,
        type: 'success'
      });
    }
  }
}
</script>

<style lang="less" scoped>
#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 700px;
}

.mapSearch {
  display: flex;
  margin-bottom: 8px;

  .el-button {
    margin-left: 8px;
  }
}

#tishikuang {
  display: block;
}

#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}

#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}
</style>
